package ru.voronoy.thefifteen.gui;

import java.awt.BorderLayout;
import java.io.File;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import ru.voronoy.thefifteen.entity.Record;

public class RecordsFrame extends JFrame {
	private List<Record> recordList = new LinkedList<Record>();
	final RecordsTableModel model = new RecordsTableModel();

	public RecordsFrame() {
		setTitle("Рекорды");
		setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
		setLocationByPlatform(true);

		JPanel basePanel = new JPanel();
		basePanel.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
		basePanel.setLayout(new BorderLayout());
		add(basePanel);

		getRecords();
		final JTable table = new JTable(model);
		JScrollPane pane = new JScrollPane(table);

		basePanel.add(pane);
	}

	private void getRecords() {
		try {
			File file = new File("records.xml");
			recordList.clear();
			if (file.exists()) {
				DocumentBuilder builder = null;
				DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
				builder = f.newDocumentBuilder();

				Document doc = builder.parse(file);
				Element root = doc.getDocumentElement();

				NodeList children = root.getChildNodes();

				String name = "";
				String result = "";
				for (int i = 0; i < children.getLength(); i++) {
					if (children.item(i).getNodeName().equals("name")) {
						name = children.item(i).getTextContent();
					}
					if (children.item(i).getNodeName().equals("result")) {
						result = children.item(i).getTextContent();
					}
					if (i % 2 == 1) {
						recordList.add(new Record(name, result));
					}
				}
				model.setDataSource(recordList);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}

	private static final int DEFAULT_WIDTH = 250;
	private static final int DEFAULT_HEIGHT = 300;
}
